import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { Storage, STORAGE_KEYS } from '../utils/storage';
import { User, AdminUser, Role } from '../types';
import { mockRoles } from '../services/mockData';

interface ProtectedRouteProps {
  children: React.ReactNode;
  requireAuth?: boolean;
  requireAdmin?: boolean;
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ 
  children, 
  requireAuth = false, 
  requireAdmin = false 
}) => {
  const location = useLocation();

  if (requireAdmin) {
    const adminUser = Storage.get<AdminUser>(STORAGE_KEYS.ADMIN_USER);
    if (!adminUser) {
      return <Navigate to="/admin/login" state={{ from: location }} replace />;
    }
    // 权限校验
    const roles = Storage.get<Role[]>(STORAGE_KEYS.ROLES) || mockRoles;
    const role = roles.find(r => r.id === adminUser.roleId) || roles[0];
    // 路径与权限映射
    const pathPermissionMap: Record<string, string> = {
      '/admin': 'dashboard',
      '/admin/products': 'product',
      '/admin/categories': 'category',
      '/admin/orders': 'order',
      '/admin/roles': 'role',
    };
    const pathname = location.pathname.split('?')[0];
    const permission = pathPermissionMap[pathname];
    if (permission && !role.permissions.includes(permission as any)) {
      return <div style={{textAlign:'center',padding:'80px 0'}}>无权限访问</div>;
    }
  } else if (requireAuth) {
    const user = Storage.get<User>(STORAGE_KEYS.USER);
    if (!user) {
      return <Navigate to="/login" state={{ from: location }} replace />;
    }
  }

  return <>{children}</>;
};

export default ProtectedRoute;
